package com.ten_4_4.hiring.talent.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import com.ten_4_4.hiring.comm.HiringConstants;
import com.ten_4_4.hiring.comm.PageModel;
import com.ten_4_4.hiring.comm.util.CommUtil;
import com.ten_4_4.hiring.comm.util.TalentUtil;
import com.ten_4_4.hiring.company.po.ApplicationPo;
import com.ten_4_4.hiring.company.service.ApplicationService;
import com.ten_4_4.hiring.talent.po.ResumePo;
import com.ten_4_4.hiring.talent.po.TalentPo;
import com.ten_4_4.hiring.talent.service.ResumeService;
import com.ten_4_4.hiring.talent.service.TalentService;


public class TalentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private TalentService talentService = new TalentService();
	private ResumeService resumeService = new ResumeService();
	private String oldEmail;

	private ApplicationService applicationService = new ApplicationService();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding(HiringConstants.ENCODE_UTF8);
		String act = request.getParameter("act");
		if("toLoginPage".equals(act)) {
			toLoginPage(request, response);
		} else if("login".equals(act)) {
			login(request, response);
		} else if("logout".equals(act)) {
			logout(request, response);
		} else if ("register".equals(act)) {
			register(request, response);
		} else if ("goHome".equals(act)) {  // 网站首页
			goHome(request, response);
		} else if ("toRegisterPage".equals(act)) {
			toRegisterPage(request, response);
		} else if ("toUserPage".equals(act)) {  // 个人首页
			toUserPage(request, response);
		} else if ("toAccountSetPage".equals(act)) {
			toAccountSetPage(request, response);
		} else if ("toPersonInfoPage".equals(act)) {
			toPersonInfoPage(request, response);
		} else if ("toFindPasswordPage".equals(act)) {
			toFindPasswordPage(request, response);
		} else if ("toResetPasswordPage".equals(act)) {
			toResetPasswordPage(request, response);
		} else if ("toOwnDeliverPositionPage".equals(act)) {
			toOwnDeliverPositionPage(request, response);
		} else if ("modifyPassword".equals(act)) {
			modifyPassword(request, response);
		} else if ("resetPassword".equals(act)) {
			resetPassword(request, response);
		} else if ("modifyEmail".equals(act)) {
			modifyEmail(request, response);
		} else if ("modifyPhone".equals(act)) {
			modifyPhone(request, response);
		} else if ("modifyNickname".equals(act)) {
			modifyNickname(request, response);
		} else if ("saveBaseInfo".equals(act)) {
			saveBaseInfo(request, response);
		} else if ("findPasswordByEmail".equals(act)) {
			findPasswordByEmail(request, response);
		} else if ("showAllResumes".equals(act)) {
			showAllResumes(request, response);
		} else if ("deleteApplication".equals(act)) {
			deleteApplication(request, response);
		} else if ("deliveryResume".equals(act)) {
			deliveryResume(request, response);
		}
	}

	private void deliveryResume(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		if(TalentUtil.getTalentPoFromSession(request) == null) {
			response.sendRedirect("TalentServlet?act=toLoginPage");
			return;
		}
		String positionIdStr = request.getParameter("positionId");
		String resumeIdStr = request.getParameter("resumeId");
		if(positionIdStr == null || resumeIdStr == null || positionIdStr.matches("\\D+") || resumeIdStr.matches("\\D+")) {
			System.out.println("参数错误");
			response.sendError(500);
			return;
		}
		int positionId = Integer.parseInt(positionIdStr);
		int resumeId = Integer.parseInt(resumeIdStr);
		int talentId = TalentUtil.getTalentPoIdFromSession(request);
		int row = applicationService.deliveryResume(positionId, talentId, resumeId);
		if(row == 1) {
			response.sendRedirect("SiteServlet?act=showPositionDetail&positionId=" + positionId);
		}
	}

	private void deleteApplication(HttpServletRequest request, HttpServletResponse response) throws IOException {
		if(TalentUtil.getTalentPoFromSession(request) == null) {
			response.sendRedirect("TalentServlet?act=toLoginPage");
			return;
		}
		String applicationId = request.getParameter("applicationId");
		if(applicationId == null || applicationId.matches("\\D+")) {
			response.sendError(500);
			return;
		}
		int row = applicationService.deleteApplication(Integer.parseInt(applicationId));
		if(row == 0) {
			response.getWriter().println("fail");
		}
	}

	private void toOwnDeliverPositionPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		TalentPo talent = TalentUtil.getTalentPoFromSession(request);
		if(talent == null) {
			response.sendRedirect("TalentServlet?act=toLoginPage");
			return;
		}
		String pageNoStr = request.getParameter("pageNo");
		PageModel<ApplicationPo> applicationListPageModel = null;
		if(pageNoStr == null) {
			applicationListPageModel = applicationService .listTalentPositionPaging(talent.getId(), HiringConstants.DEFAULT_PAGE_NO, HiringConstants.DEFAULT_PAGE_SIZE);
		} else {
			int pageNo = Integer.parseInt(pageNoStr);
			applicationListPageModel = applicationService.listTalentPositionPaging(talent.getId(), pageNo, HiringConstants.DEFAULT_PAGE_SIZE);
		}
		request.setAttribute("applicationListPageModel", applicationListPageModel);
		request.getRequestDispatcher("WEB-INF/view/talent/talent-all-position.jsp").forward(request, response);
	}

	private void showAllResumes(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(TalentUtil.getTalentPoFromSession(request) == null) {
			response.sendRedirect("TalentServlet?act=toLoginPage");
			return;
		}
		int talentId = TalentUtil.getTalentPoIdFromSession(request);
		List<ResumePo> resumeList = resumeService.listAllResume(talentId);
		request.setAttribute("resumeList", resumeList);
		request.getRequestDispatcher("WEB-INF/view/talent/talent-all-resumes.jsp").forward(request, response);
	}

	private void resetPassword(HttpServletRequest request, HttpServletResponse response) throws IOException {
		TalentPo talentPo = talentService.findTalentByEmail(oldEmail);
		if(talentPo == null) {
			// FIXME
			System.out.println("查无此人！");
			return;
		}
		String password = request.getParameter("password");
		int result = talentService.modifyPassword(talentPo.getId(), password);
		if(result == 0) {
			// FIXME
			System.out.println("修改失败！");
			response.sendRedirect("404.jsp");
			return;
		}
		response.sendRedirect("TalentServlet?act=toLoginPage");
	}

	private void toResetPasswordPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("WEB-INF/view/talent/talent-reset-password.jsp").forward(request, response);
	}

	private void findPasswordByEmail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String email = request.getParameter("email");
		oldEmail = email;
		// 定义发送简单邮件对象
		HtmlEmail htmlEmail = new HtmlEmail();

	    // 设置SMTP服务器,比如:smtp.163.com
		htmlEmail.setHostName("smtp.163.com");
	    // 设置登入认证服务器的用户名和密码
		htmlEmail.setAuthentication("qq903441294@163.com", "QQ1294senha");

	    // 默认是25端口
		htmlEmail.setSmtpPort(25);
	    // SSL enabled SMTP server,即如果是支持SSL服务器的端口是465
	    try {
			// 设置发送人邮箱和名字
	    	htmlEmail.setFrom("qq903441294@163.com", "吓一跳丸子", "utf-8");

			// 设置收件人可以是多个
	    	htmlEmail.addTo(email);

			// 设置发送主题
	    	htmlEmail.setSubject("更改密码");
			// 设置发送主体内容
			StringBuffer msg = new StringBuffer();
			msg.append("<p>Hi, ");
			msg.append(email.substring(0, email.indexOf("@")));
			msg.append(": </p>");
			msg.append("<p>我们已经收到你的找回密码请求，请");
			String link = "http://localhost:8080/hiring_git/TalentServlet?act=toResetPasswordPage";
			msg.append("<a href='");
			msg.append(link);
			msg.append("'>点击此链接重置密码</a>。</p>");
			msg.append("<p>（本连接将在1天后失效）</p>");
			htmlEmail.setContent(msg.toString(), "text/html;charset=utf-8");

			// 确定发送邮件动作
			htmlEmail.send();
		} catch (EmailException e) {
			request.setAttribute("msgSendStatus", "failed");
			request.getRequestDispatcher("WEB-INF/view/talent/talent-find-password.jsp").forward(request, response);
			e.printStackTrace();
		}
	    request.setAttribute("msgSendStatus", "success");
	    request.setAttribute("email", email);
	    request.getRequestDispatcher("WEB-INF/view/talent/talent-find-password-status.jsp").forward(request, response);
	}

	private void toFindPasswordPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("WEB-INF/view/talent/talent-find-password.jsp").forward(request, response);
	}

	private void saveBaseInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
		if(TalentUtil.getTalentPoFromSession(request) == null) {
			response.sendRedirect("TalentServlet?act=toLoginPage");
			return;
		}
		String name = request.getParameter("name");
//		String phone = request.getParameter("phone");  // 手机号码不应该在此处被修改
//		String email = request.getParameter("email");  // 邮箱地址不应该在此处被修改
		String ageStr = request.getParameter("age");
		if(ageStr == null || ageStr.matches("\\D+")) {
			// FIXME
			System.out.println("格式错误！");
			return;
		}
		int age = Integer.parseInt(ageStr);
		// String hobby = request.getParameter("hobby");
		String[] hobbys = request.getParameterValues("hobbys");
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < hobbys.length - 1; i++) {
			sb.append(hobbys[i]).append("|");
		}
		sb.append(hobbys[hobbys.length - 1]);
		String hobby = sb.toString();
		String genderStr = request.getParameter("gender"); 
		if(genderStr == null || genderStr.matches("\\D+")) {
			// FIXME
			System.out.println("格式错误！");
			return;
		}
		int gender = Integer.parseInt(genderStr);
		TalentPo talentPo = new TalentPo();
		talentPo.setId(TalentUtil.getTalentPoIdFromSession(request));
		talentPo.setName(name);
//		talentPo.setPhone(phone);
//		talentPo.setEmail(email);
		talentPo.setAge(age);
		talentPo.setHobby(hobby);
		talentPo.setGender(gender);
		int row = talentService.saveBaseInfo(talentPo);
		if(row == 1) {
			TalentPo tempPo = TalentUtil.getTalentPoFromSession(request);
			tempPo.setName(name);
//			tempPo.setPhone(phone);
//			tempPo.setEmail(email);
			tempPo.setAge(age);
			tempPo.setHobby(hobby);
			tempPo.setGender(gender);
			response.sendRedirect("TalentServlet?act=toPersonInfoPage");
		} else {
			response.sendRedirect("404.jsp");
		}
	}

	private void modifyPassword(HttpServletRequest request, HttpServletResponse response) throws IOException {
		if(TalentUtil.getTalentPoFromSession(request) == null) {
			response.sendRedirect("TalentServlet?act=toLoginPage");
			return;
		}
		int talentId = TalentUtil.getTalentPoIdFromSession(request);
		String password = request.getParameter("password");
		String oldPassword = request.getParameter("oldPassword");
		if(!TalentUtil.getTalentPoFromSession(request).getPassword().equals(oldPassword)) {
			// FIXME
			System.out.println("密码匹配错误");
			response.sendError(500);
			return;
		}
		int row = talentService.modifyPassword(talentId, password);
		if(row == 1) {
			TalentUtil.getTalentPoFromSession(request).setPassword(password);
			response.sendRedirect("TalentServlet?act=toAccountSetPage");
		} else {
			response.sendError(404);
		}
	}
	private void modifyNickname(HttpServletRequest request, HttpServletResponse response) throws IOException {
		if(TalentUtil.getTalentPoFromSession(request) == null) {
			response.sendRedirect("TalentServlet?act=toLoginPage");
			return;
		}
		int talentId = TalentUtil.getTalentPoIdFromSession(request);
		String nickname = request.getParameter("nickname");
		int row = talentService.modifyNickname(talentId, nickname);
		if(row == 1) {
			TalentUtil.getTalentPoFromSession(request).setNickname(nickname);
			response.sendRedirect("TalentServlet?act=toAccountSetPage");
		} else {
			response.sendError(404);
		}
	}
	private void modifyEmail(HttpServletRequest request, HttpServletResponse response) throws IOException {
		if(TalentUtil.getTalentPoFromSession(request) == null) {
			response.sendRedirect("TalentServlet?act=toLoginPage");
			return;
		}
		int talentId = TalentUtil.getTalentPoIdFromSession(request);
		String email = request.getParameter("email");
		int row = talentService.modifyEmail(talentId, email);
		if(row == 1) {
			TalentUtil.getTalentPoFromSession(request).setEmail(email);
			response.sendRedirect("TalentServlet?act=toAccountSetPage");
		} else {
			response.sendError(404);
		}
	}
	private void modifyPhone(HttpServletRequest request, HttpServletResponse response) throws IOException {
		if(TalentUtil.getTalentPoFromSession(request) == null) {
			response.sendRedirect("TalentServlet?act=toLoginPage");
			return;
		}
		int talentId = TalentUtil.getTalentPoIdFromSession(request);
		String phone = request.getParameter("phone");
		int row = talentService.modifyPhone(talentId, phone);
		if(row == 1) {
			TalentUtil.getTalentPoFromSession(request).setPhone(phone);
			response.sendRedirect("TalentServlet?act=toAccountSetPage");
		} else {
			response.sendError(404);
		}
	}

	private void toPersonInfoPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(TalentUtil.getTalentPoFromSession(request) == null) {
			response.sendRedirect("TalentServlet?act=toLoginPage");
			return;
		}
		request.getRequestDispatcher("WEB-INF/view/talent/talent-person-info.jsp").forward(request, response);
	}

	private void toAccountSetPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(TalentUtil.getTalentPoFromSession(request) == null) {
			response.sendRedirect("TalentServlet?act=toLoginPage");
			return;
		}
		request.getRequestDispatcher("WEB-INF/view/talent/talent-account-set.jsp").forward(request, response);
	}

	private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.getSession().invalidate();
		response.sendRedirect("TalentServlet?act=goHome");
	}

	private void toUserPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(TalentUtil.getTalentPoFromSession(request) == null) {
			response.sendRedirect("TalentServlet?act=toLoginPage");
			return;
		}
		request.getRequestDispatcher("WEB-INF/view/talent/talent-homepage.jsp").forward(request, response);
	}

	private void toRegisterPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("WEB-INF/view/talent/talent-register.jsp").forward(request, response);
	}

	private void goHome(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("SiteServlet?act=toSiteHomepage").forward(request, response);
	}

	private void toLoginPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("WEB-INF/view/talent/talent-login.jsp").forward(request, response);
	}

	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String code = request.getParameter("code");
		String password = request.getParameter("password");
		TalentPo talentPo = new TalentPo();
		talentPo = talentService.login(code, password);
		if(talentPo == null) { 
			request.setAttribute("errorInfo", "该用户不存在！");
			request.getRequestDispatcher("TalentServlet?act=toLoginPage").forward(request, response);
			return;
		}
		request.getSession().setAttribute("talentPo", talentPo);
		response.sendRedirect("SiteServlet?act=toSiteHomepage");
	}

	private void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String rand = (String) CommUtil.getAttributeFromSession(request, "rand");
		String captcha = request.getParameter("captcha");
		if(rand != null) {
			if(!rand.equals(captcha)) {
				request.setAttribute("errorInfo", "验证码输入错误！");
				request.getRequestDispatcher("TalentServlet?act=toRegisterPage").forward(request, response);
				return;
			}
		} else {
			request.setAttribute("errorInfo", "验证码生成失败！");
			request.getRequestDispatcher("TalentServlet?act=toRegisterPage").forward(request, response);
			return;
		}
		CommUtil.removeAttributeFromSession(request, "rand");
		String nickname = request.getParameter("nickname");
		String code = request.getParameter("code");
		String password = request.getParameter("password");
		TalentPo talentPo = talentService.register(code, password, nickname);
		if(talentPo == null) { 
			response.sendError(500);
			return;
		}
		request.getSession().setAttribute("talentPo", talentPo);
		response.sendRedirect("TalentServlet?act=toUserPage");
	}

}
